﻿using MCMesServer.DBFunctions.DBFuncs;
using MCMesServer.DBFunctions.TransformFuncs;
using MCMesServer.Model;
using MCMesServer.NetConnectFunc;
using MCMesServer.PublicLogInfo;
using MCMesServer.WorkMessageSaveFunc;
using MesDAL.DTO.ProcessSheet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MCMesServer.ServerReceiveFunctions.PromoteProcessSheet
{
    public class PromoteProcessSheetHandlerFunc
    {
        public static void HandleReceiveMsg(ServerModel model, IntPtr connId)
        {
            try
            {
                switch (model.Operation)
                {
                    case Operations.DownloadProcessForm:
                        ReceiveDownloadProcessForm(model, connId);
                        break;
                    case Operations.DownloadWorkpieceImage:
                        ReceiveDownloadWorkpieceImage(model, connId);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                PublicLogInfoFunc.RecordManualErrorMessage($"[{model.Step}]发生接收错误，错误信息内容：{model.Message}", ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 下载工艺单
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public async static void ReceiveDownloadProcessForm(ServerModel model, IntPtr connId)
        {
            try
            {
                WorkpieceDTO workpiece = TransformModelFunc<WorkpieceDTO>.TransformString2ModelFunc(model.Message);
                WorkpieceDTO selectWorkpiece = await WorkPieceDBFunc.SelectWorkPieceByNumberAndOrder(workpiece.number, workpiece.order);
                if (selectWorkpiece is null)
                {
                    ServerModel sendModel = new ServerModel()
                    {
                        MachineNum = model.MachineNum,
                        Step = model.Step,
                        Operation = model.Operation,
                        ResCode = ServerResCode.ERR_NullWorkpiece,
                    };
                    CommonConnectFunc.SendInterServerModelFunc(connId, sendModel);
                }
                else
                {
                    List<ProcessSheetDTO> processList = await ProcessSheetDBFunc.SelectProcessSheetListByWorkpiece(selectWorkpiece);
                    ProcessForm processForm = new ProcessForm()
                    {
                        workpiece = selectWorkpiece,
                        processList = processList,
                    };
                    ServerModel sendModel = new ServerModel()
                    {
                        Step = model.Step,
                        MachineNum = model.MachineNum,
                        Operation = model.Operation,
                        Message = TransformModelFunc<ProcessForm>.TransformModel2StringFunc(processForm)
                    };
                    CommonConnectFunc.SendInterServerModelFunc(connId, sendModel);
                }
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }

        /// <summary>
        /// 下载工艺单图片
        /// </summary>
        /// <param name="model"></param>
        /// <param name="connId"></param>
        public static void ReceiveDownloadWorkpieceImage(ServerModel model, IntPtr connId)
        {
            try
            {
                string CommonPath = ConfigClass.ReadIniData("SaveImagePath", "Path", MainWindow.ConfigPath);
                string number = model.Message;
                string pngPath = CommonPath + "\\" + number + "\\" + number + ".png";

                bool IsExists = File.Exists(pngPath);
                if (IsExists)
                {
                    using (Bitmap bitmap = new Bitmap(pngPath))
                    {
                        byte[] imageArray = WorkPieceImageSaveFunc.ConvertImage2ByteArray(bitmap);
                        int pos = 0;
                        while (pos < imageArray.Length)
                        {
                            byte[] sendArray = new byte[1024 * 10];
                            ServerModel sendImageModel = new ServerModel()
                            {
                                Step = model.Step,
                                MachineNum = model.MachineNum,
                                Operation = model.Operation,
                            };
                            if (pos == 0)
                            {
                                if (pos + sendArray.Length >= imageArray.Length)
                                {
                                    sendImageModel.Message = "Finish;" + number + ";" + pos;
                                }
                                else
                                {
                                    sendImageModel.Message = "Start;" + number + ";" + pos;
                                }
                                Array.Copy(imageArray, pos, sendArray, 0, sendArray.Length);
                                sendImageModel.Data = sendArray;
                            }
                            else if (pos + sendArray.Length >= imageArray.Length)
                            {
                                Array.Copy(imageArray, pos, sendArray, 0, imageArray.Length - pos);
                                sendImageModel.Message = "Finish;" + number + ";" + pos;
                                sendImageModel.Data = sendArray;
                            }
                            else
                            {
                                sendImageModel.Message = "Normal;" + number + ";" + pos;
                                Array.Copy(imageArray, pos, sendArray, 0, sendArray.Length);
                                sendImageModel.Data = sendArray;
                            }
                            pos += sendArray.Length;
                            CommonConnectFunc.SendInterServerModelFunc(connId, sendImageModel);
                        }
                    }
                }
                else
                {
                    ServerModel serverModel = new ServerModel()
                    {
                        Step = model.Step,
                        MachineNum = model.MachineNum,
                        Operation = model.Operation,
                        ResCode = ServerResCode.ERR_NullImageInServer,
                    };
                    CommonConnectFunc.SendInterServerModelFunc(connId, serverModel);
                }
            }
            catch (Exception ex)
            {
                CommonConnectFunc.SendServerError(connId, model.MachineNum, model.Operation, model.Step, ServerResCode.ERR_UnExpectOfState, ex.ToString());
                return;
            }
        }
    }
}
